package com.chenwut.threadDemo.exercise_5;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

/**
 * @author ChenPi
 * @since 2024/09/20 09:09
 */
public class MyThread extends Thread {

    //{10,5,20,50,100,200,500,800,2,80,300,70}
    static ArrayList<Integer> list = new ArrayList<>();

    static {

        Collections.addAll(list, 10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300, 70);
    }

    @Override
    public void run() {
        while (true) {
            synchronized (MyThread.class) {
                if (list.size() == 0) {
                    break;
                }
                if (list.size() > 0) {
                    Random r = new Random();
                    int index = r.nextInt(list.size());
                    System.out.println(getName() + " 又产生了一个大奖：" + list.get(index));
                    list.remove(index);
                }
            }
            // 写在锁里面，线程不会释放锁，其他线程无法获得锁处于等待状态
            // 写到锁外面，此时已经释放了锁，当前线程会睡眠，不参与竞争，其他线程可以获得锁，继续竞争
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
